package one.stand.controller;

import com.jmp.base.ArticleApi;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.AccountFeign;
import com.jmp.feign.SecurityFeign;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.TemplateFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.dto.*;
import one.stand.enums.LoginEnum;
import one.stand.mapper.ArticleMapperExt;
import one.stand.model.*;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author cjr
 */
@Slf4j
@Api(description = "红木头条H5分享")
@RestController
@RequestMapping("lead/h5")
public class LeadController {
    @Autowired
    private SecurityFeign securityFeign;
    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private ArticleMapperExt articleMapperExt;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;

    @ApiOperation(value = "详情")
    @PostMapping("/detail")
    public ResultModel<LeadDetailH5Response> detailH5(@RequestBody LeadDetailH5Request request) {

        LeadDetailH5Response.LeadDetailH5ResponseBuilder responseBuilder = LeadDetailH5Response.builder();

        //头条
        ArticleWithBLOBs article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
        if (Objects.nonNull(article) && ArticleApi.STATUS_UP == article.getStatus()) {
            responseBuilder.hasArticle(true)
                    .title(article.getTitle())
                    .origin(article.getOriginName())
                    .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                    .content(article.getContent())
                    .originUrl(article.getOriginUrl());
        } else {
            responseBuilder.hasArticle(false);
        }

        //分享人
        if (Objects.nonNull(request.getShareCardId()) || Objects.nonNull(request.getUserId())) {
            BusinessCard cardModel;
            if (Objects.nonNull(request.getShareCardId())) {
                cardModel = businessCardBaseService.getCustomer(request.getShareCardId());
            } else {
                cardModel = businessCardBaseService.getByUserId(request.getUserId());
            }

            //user
            UserDto user = userAdminService.get(Objects.nonNull(cardModel) ? cardModel.getUserId() : request.getUserId());
            responseBuilder.img(user.getUserImg())
                    .name(user.getName())
                    .tel(user.getPhone());

            if (Objects.nonNull(cardModel)) {//company exist
                Company company = companyBaseService.getById(cardModel.getCompanyId());

                AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                        .companyId(cardModel.getCompanyId())
                        .loginEnum(LoginEnum.USER)
                        .build();
                ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
                String wechatId = accountResponseResultModel.isSuccess() ? accountResponseResultModel.getData().getWechatId() : null;

                TemplateGet2Request getRequest = TemplateGet2Request.builder()
                        .templateType(TemplateApi.Type.ID_ARTICLE_H5_CARD)
                        .cardId(cardModel.getCardId())
                        .build();
                ResultModel<TemplateGetResponse> templateGetResponseResultModel = templateFeign.get2(getRequest);
                String cardUrl = templateGetResponseResultModel.isSuccess() ? templateGetResponseResultModel.getData().getImageUrl() : null;
                String wxcodeUrl = null;
                if (StringUtils.isNoneBlank(cardModel.getWxCode())) {
                    getRequest = TemplateGet2Request.builder()
                            .templateType(TemplateApi.Type.ID_ARTICLE_H5_WXCODE)
                            .cardId(cardModel.getCardId())
                            .build();
                    templateGetResponseResultModel = templateFeign.get2(getRequest);
                    if (templateGetResponseResultModel.isSuccess()) {
                        wxcodeUrl = templateGetResponseResultModel.getData().getImageUrl();
                    }
                }

                final RequestContext requestContext = RequestContextHolder.getRequestContext();
                RequestContext.User contextUser = requestContext.getUser();
                if (!requestContext.isSelf(user.getUserId())) {//非本人查看时
                    SeeRecordLeadRequest leadRequest = SeeRecordLeadRequest.builder()
                            .userId(contextUser.getUserId())
                            .cardId(cardModel.getCardId())
                            .companyId(cardModel.getCompanyId())
                            .articleId(request.getArticleId())
                            .build();
                    seeRecordFeign.lead(leadRequest);
                }

                responseBuilder.position(cardModel.getPosition())
                        .companyName(company.getCompanyName())
                        .tel(cardModel.getPhone())
                        .cardUrl(cardUrl)
                        .wxCodeCardUrl(wxcodeUrl)
                        .wechatId(wechatId)
                        .oneWechat(companyBaseService.isOneWechat(cardModel.getCompanyId()))
                        .openImgFlag(BooleanUtils.toInteger(companyBaseService.isByLabel(company.getCompanyId(), CompanyBaseService.LABEL_SUPPLIER)
                                || companyBaseService.isByLabel(company.getCompanyId(), CompanyBaseService.LABEL_JXS)));
            } else {
                responseBuilder.openImgFlag(BooleanUtils.toInteger(true));
            }
        }

        return ResultModel.success(responseBuilder.build());
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public ResultModel<LeadH5LoginResponse> login(@RequestBody LeadH5LoginRequest request) {
        SecurityLoginGzhApiRequest wxRequest = SecurityLoginGzhApiRequest.builder()
                .code(request.getCode())
                .loginEnum(LoginEnum.H5_LEAD)
                .build();
        ResultModel<SecurityLoginGzhApiResponse> result = securityFeign.loginGzhApiWx(wxRequest);
        AssertUtil.isTrue(result);

        LeadH5LoginResponse loginResponse = LeadH5LoginResponse.builder()
                .token(result.getData().getToken())
                .build();
        return ResultModel.success(loginResponse);
    }

    @ApiOperation("转发")
    @PostMapping("/forward")
    public ResultModel<LeadH5ForwardResponse> forward(@RequestBody LeadH5ForwardRequest request) {
        log.info("id:{}", request.getId());
        ArticleWithBLOBs article = articleMapperExt.selectByPrimaryKey(request.getId());

        LeadH5ForwardResponse loginResponse = LeadH5ForwardResponse.builder()
                .shareTitle(article.getTitle())
                .shareImg(article.getShareCard())
                .shareDesc(article.getSubtitle())
                .build();
        return ResultModel.success(loginResponse);
    }
}
